<template>
  <div>
    <!-- 页面主体 -->
    <Content :style="{ minHeight: '280px', background: '#fff'}">
      <Layout>
        <!-- 左侧树型菜单 -->
        <Sider hide-trigger :style="{padding: '24px',background: '#fff'}">
          <Menu active-name="1-2" theme="light" width="auto" :open-names="['1']">
            <Tree :data="treeData" @on-select-change="onSelectChange"></Tree>
          </Menu>
        </Sider>
        <!-- 右侧产品信息 -->
        <Content :style="{padding: '24px', minHeight: '280px', background: '#fff'}">
          <!-- 搜索框 -->
          <h3 style="color:#2d8cf0;margin-bottom:5px;">产品搜索：</h3>
          <div style="height:40px;margin-bottom:5px;">
            <Input v-model="data.title" style="width:400px;" placeholder="请输入产品标题进行搜索...">
              <Button slot="append" icon="close" @click="searchReset"></Button>
            </Input>
            <Button type="primary" icon="ios-search" @click="search" style="position: relative; left: 405px; top: -31px;">搜索</Button>
          </div>
          <!-- 添加、删除按钮 -->
          <div style="margin-bottom:10px;">
            <Button type="success" @click="modal1=true" style="margin-right:10px;width:80px;">添加</Button>
            <Button type="error" @click="removes" style="width:80px">删除</Button>
          </div>
          <!-- 对话框 -->
          <Modal v-model="modal1" title="产品信息" @on-ok="ok" @on-cancel="cancel">
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
              <FormItem label="产品分类:" prop="cateId">
                <Input type="text" v-model="formValidate.cateId" placeholder="请输入产品所属分类..." disabled></Input>
              </FormItem>
              <FormItem label="产品标题:" prop="title">
                <Input type="text" v-model="formValidate.title" placeholder="请输入产品标题..."></Input>
              </FormItem>
              <FormItem label="产品价格:" prop="price">
                <Input type="text" v-model="formValidate.price" placeholder="请输入产品价格(人民币)，建议保留两位小数..." number></Input>
              </FormItem>
              <FormItem label="图片信息:" prop="imgurl">
                <!-- <Input type="text" v-model="formValidate.imgurl" placeholder="请输入产品图片地址"></Input> -->
                <!-- 改为在线编辑器，可以添加文字、图片等信息 -->
                <quill-editor :content="formValidate.imgurl" @change="onEditorChange($event)" ></quill-editor>
              </FormItem>
              <FormItem>
                <Button type="primary" @click="handleSubmit('formValidate')">提交</Button>
                <Button type="ghost" @click="handleReset('formValidate')" style="margin-left: 8px">重置</Button>
              </FormItem>
            </Form>
          </Modal>
          <!-- 产品列表 -->
          <Table id="list" border ref="selection" :columns="columns7" :data="productdata" @on-selection-change="onSelectionChange" @></Table>
          <br/>
          <!-- 分页 -->
          <Page :total="data.total" size="small" @on-change="onChangePage" @on-page-size-change="onPageSizeChange" show-elevator show-sizer></Page>
        </Content>
      </Layout>
    </Content>
  </div>
</template>

<script>
  export default {
    data () {
      //产品价格验证
      var validatePrice = (rule, value, callback) => {
        if (!value) {
            return callback(new Error('产品价格不能为空'));
        }
        // 模拟异步验证
        setTimeout(() => {
          if (Number.isNaN(value)) {//判断不是一个数字
            callback(new Error('请输入数值'));
          } else {
            callback();
          }
        }, 500);
      };
      return {
        //树型菜单
        treeData:[],
        //添加商品对话框
        formValidate: {
          title: '',
          price: '',
          imgurl: '',
          cateId: 0
        },
        ruleValidate: {
          title: [
            { required: true, message: '标题不能为空', trigger: 'blur' }
          ],
          price: [
            { required: true, validator: validatePrice, trigger: 'blur' }
          ],
          imgurl: [
            { required: true, message: '图片地址不能为空', trigger: 'blur' }
          ],
          cateId:[
            { required: true }
          ]
        },
        modal1:false,
        //产品列表
        columns7: [
          {
            type: 'selection',
            width: 60,
            align: 'center'
          },
          {
            title: '标题',
            key: 'title',
            align: 'center'
          },
          {
            title: '价格（人民币:元）',
            key: 'price',
            align: 'center',
            render: (h, params) => {//添加￥符号
              return h("div", [
                h("Icon", {
                  props: {
                    type: "social-yen",
                    color: "#ed3f14"
                  }
                }),
                h("span", params.row.price.toFixed(2))
              ]);
            }
          },
          {
            title: '图片信息',
            key: 'imgurl',
            align: 'center',
            type:'html'/* ,
            render: (h, params) => {
              return h('div', [
                  h('Button', {
                      props: {
                          type: 'primary',
                          size: 'small'
                      },
                      style: {
                          marginRight: '5px'
                      },
                      on: {
                          click: () => {
                              this.show(params.row)
                          }
                      }
                  }, 'View'),
                  h('div', params.row.imgurl)
              ]);
            } */
          },
          {
            title: '操作',
            key: 'action',
            width: 150,
            align: 'center',
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.edit(params)
                    }
                  }
                }, '修改'),
                h('Button', {
                  props: {
                    type: 'error',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.remove(params)
                    }
                  }
                }, '删除')
              ]);
            }
          }
        ],
        //产品信息
        productdata:[],
        //产品多选
        ids:[],
        //翻页
        data:{
          cateId:0,
          title:'',
          total:0,
          page:1,
          limit:10
        }
      }
    },
    //生命周期钩子函数
    created(){
      this.getTree();
      this.getData();
    },
    methods: {
      // 获取树型菜单
      getTree(){
        this.$http.post('http://10.31.153.35:3000/cate/list/2').then((response) => {
          this.treeData = response.data;
          this.treeData[0].expand = true;
        })
      },
      //获取商品数据
      getData(){
        this.$http({
          method:'post',
          url:'http://10.31.153.35:3000/product/list',
          data:this.data
        }).then((response) => {
          this.productdata = response.data.docs;
          this.data.total = response.data.total;
        })
      },
      //显示图片信息
      /* show (index) {
        this.$Modal.info({
          title: 'Img Info',
          content: `${this.productdata[index].imgurl}`
        })
      }, */
      //编辑
      edit(params){
        this.formValidate = params.row;
        this.modal1 = true;
      }, 
      //删除
      remove (params) {
        this.$Modal.confirm({
          title: 'Title',
          content: '<p>确认删除？</p>',
          onOk: () => {
            var id=params.row._id;
            this.$http.delete(`http://10.31.153.35:3000/product/data/${id}`).then((response) => {
              this.$Message.info('删除成功');
              this.getData()
            })
          },
          onCancel: () => {
            this.$Message.info('取消删除');
          }
        });
      },
      //添加商品对话框
      ok(){
        this.$Message.info('Clicked ok');
      },
      cancel(){
        this.$Message.info('Clicked cancel');
      },
      //对话框表单
      handleSubmit (name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            if(this.formValidate._id){
              let id=this.formValidate._id;
              this.$http.put(`http://10.31.153.35:3000/product/data/${id}`,this.formValidate).then((response) => {
                this.$Message.success('更新!');
                //重置form表单为初始值状态
                Object.assign(this.$data.formValidate,this.$options.data().formValidate);
                this.getData();
              })
            }else{
              this.$http.post('http://10.31.153.35:3000/product/data',this.formValidate).then((response) => {
                this.$Message.success('创建!');
                Object.assign(this.$data.formValidate,this.$options.data().formValidate);
                this.getData();
              })
            }
          }else {
            this.$Message.error('失败!');
          }
        })
      },
      //在线编辑器---添加图片
      onEditorChange({ quill, html, text }) {
        this.formValidate.imgurl = html;
      },
      //重置对话框表单
      handleReset (name) {
        //this.$refs[name].resetFields();
        Object.assign(this.$data.formValidate,this.$options.data().formValidate);
      },
      //商品搜索
      search(){
        this.getData();
      },
      //重置搜索框表单
      searchReset () {
        this.data.title='';
      },
      //商品多选
      onSelectionChange(selection){
        if(selection && selection.length > 0){
          var ids = [];
          for(let i = 0;i < selection.length;i ++){
            ids.push(selection[i]._id)
          }
          this.ids = ids;
        }
      },
      //删除多个商品
      removes(){
        this.$Modal.confirm({
          title: 'Title',
          content: '<p>确认删除多个商品？</p>',
          onOk: () => {
            this.$http({
              method:'post',
              url:'http://10.31.153.35:3000/product/data/removes',
              data:{
                ids:this.ids
              }
            }).then((res)=>{
              this.$Message.info('删除成功');
              this.getData();
            })
          },
          onCancel: () => {
            this.$Message.info('取消删除');
          }
        });
      },
      //分页
      onChangePage(page){
        this.data.page = page;
        this.$http({
          method:'post',
          url:'http://10.31.153.35:3000/product/list',
          data:this.data
        }).then(response=>{
          this.productdata = response.data.docs;
          this.data.total = response.data.total;
        })
      },
      //设置每页条数
      onPageSizeChange(pageSize){
        this.data.limit = pageSize;
        this.getData();
      },
      //树型菜单点击事件
      onSelectChange(node){
        for(let i in node){
          if (!node[i].parentId) {
            this.data.cateId = null;
            this.getData();
          } else {
            this.data.cateId = node[i]._id;
            this.formValidate.cateId = node[i]._id;
            this.getData();
          }
        }
      }
    }
  }
</script>

<style scoped>
  img{
    width:50px;
  }
</style>
